import { computed, defineComponent, provide, reactive, ref } from "vue";
import "./editor.scss";
import deepcopy from "deepcopy";
import EditorPropsSet from "./jsx/editor-props-set.jsx";
import SelfTable from "./jsx/self-table.jsx";
import SelfInspect from "./jsx/self-inspect.jsx";
import Preview from "./preview.jsx";
import EditorConfigLeft from "./jsx/editor-config-left.jsx";
import axios from "axios";
import configList from "./js/configLeft.js";
axios.defaults.baseURL = "http://182.151.11.69:31011";
import DragEvent from "./js/dragEvent.js";
import EditorEvent from "./js/editorEvent.js";

export default defineComponent({
  props: {
    modelValue: Object, // mockData `{container:"",blocks:[],propNames:[]}`
  },
  emits: ["update:modelValue", "closeEditor"],
  setup(props, ctx) {
    const data = computed({
      get() {
        return props.modelValue;
      },
      set(value) {
        ctx.emit("update:modelValue", deepcopy(value));
      },
    });
    // console.log(666, data.value);

    let lastCheckItem = ref(null);
    let dragItem = null;
    const configMap = [];
    configList.forEach((item) => {
      configMap[item.key] = item;
    });
    provide("configList", configList);
    // 创建一个ref来管理对话框的显示状态
    let showPreview = ref(false);
    const formData = reactive({
      model: {},
    });

    //将鼠标事件/逻辑事件封装到单独的对象中
    const {
      onDragstart,
      onDragover,
      onDrop,
      onMousedown,
      onMouseenter,
      clearFocus,
    } = DragEvent(dragItem, data, lastCheckItem);

    const {
      addData,
      isOnlyProp,
      recordPropName,
      removeFromBlocks,
      changeItem,
      onInput,
      onClose,
      onSubmit,
      onPreview,
    } = EditorEvent(dragItem, data, lastCheckItem, ctx, showPreview);

    const rules = reactive({
      formTitle: [
        {
          required: true,
          message: "请输入表单标题",
          trigger: "blur",
        },
      ],
      formSubtitle: [
        {
          required: false,
          message: "请输入表单描述",
          trigger: "blur",
        },
      ],
      formNeed: [
        {
          required: true,
          message: "请选择审批",
          trigger: "change",
        },
      ],
    });
    const formTitleRef = ref(null);
    const submitFormTitle = async () => {
      return new Promise((resolve, reject) => {
        formTitleRef.value.validate((valid) => {
          if (!valid) {
            reject("请完善表单内容");
          } else {
            resolve(true);
          }
        });
      });
    };

    ctx.expose({ submitFormTitle });

    // 反显dom
    return () => (
      <>
        {/* 预览 */}
        {showPreview.value && (
          <ElDialog
            beforeClose={() => {
              showPreview.value = false;
            }}
            v-model={showPreview.value}
            title="预览"
            width="50%"
          >
            <Preview
              v-model={data.value}
              isPreview={true}
              onClosePreview={() => {
                showPreview.value = false;
              }}
            ></Preview>
          </ElDialog>
        )}

        <div className="editors">
          <div className="editors-left">
            {/* 左侧配置区域 */}
            <EditorConfigLeft onAddData={addData}></EditorConfigLeft>
          </div>
          <div className="editors-center">
            {/* 中间顶部操作区域 */}
            <div className="editors-center-top">
              <>
                {/* <el-button onClick={onSubmit} type="primary">
                  提交
                </el-button>
                <el-button onClick={onInput}>导入</el-button>
                <el-button onClick={onClose}>关闭</el-button>
                <el-button type="primary" onClick={onPreview}>
                  预览
                </el-button> */}
                <ElForm
                  ref={formTitleRef}
                  rules={rules}
                  model={data.value.container}
                >
                  <ElFormItem label="" prop="formTitle">
                    <ElInput
                      placeholder="请输入表单标题，必填"
                      maxlength={20}
                      v-model={data.value.container.formTitle}
                    ></ElInput>
                  </ElFormItem>
                  <ElFormItem label="" prop="formSubtitle">
                    <ElInput
                      maxlength={50}
                      placeholder="请输入表单描述，非必填（举例：请仔细填写表单中内容）"
                      v-model={data.value.container.formSubtitle}
                    ></ElInput>
                  </ElFormItem>
                  <ElFormItem prop="formNeed" label="审批">
                    <ElRadioGroup v-model={data.value.container.formNeed}>
                      <ElRadio value="need">需要</ElRadio>
                      <ElRadio value="dontNeed">不需要</ElRadio>
                    </ElRadioGroup>
                  </ElFormItem>
                </ElForm>
              </>
            </div>

            {/* form表单区域 */}
            <div
              // onDragover={onDragover}
              // onDrop={onDrop}
              onMousedown={clearFocus}
              className="editors-center-formarea"
            >
              <ElForm
                labelPosition={data.value.container.labelPosition || "top"}
              >
                {data.value.blocks.map((block, index) => {
                  return (
                    <ElFormItem
                      // onMouseenter={(e) => {
                      //   onMouseenter(e);
                      // }}
                      onMousedown={(e) => onMousedown(e, block)}
                      className="editors-center-formarea-item"
                      style={
                        block.focus
                          ? { border: "2px dashed var(--el-color-primary)" }
                          : ""
                      }
                      label={block.label}
                    >
                      {block.labelDetail && (
                        <div className="editors-center-formarea-item-subtitle">
                          {block.labelDetail}
                        </div>
                      )}
                      {block.focus && (
                        <div
                          onClick={(e) => removeFromBlocks(index)}
                          className="editors-center-formarea-item-hint"
                        >
                          {block.label}：删除
                        </div>
                      )}
                      {{
                        input: () => (
                          <ElInput
                            // v-model={formData.model[block.propName]}
                            placeholder="请输入"
                            type={
                              block.tempType == "textarea" ? "textarea" : "text"
                            }
                          ></ElInput>
                        ),
                        select: () => (
                          <ElSelect
                          // v-model={formData.model[block.propName]}
                          >
                            <ElOption label="左对齐" value="left"></ElOption>
                            <ElOption label="顶部对齐" value="top"></ElOption>
                          </ElSelect>
                        ),
                        table: () => (
                          <SelfTable
                            // v-model={formData.model[block.propName]}
                            v-model:renders={block.value}
                          ></SelfTable>
                        ),
                        radio: () => (
                          <div style={{ width: "100%" }}>
                            <ElRadioGroup
                            // v-model={formData.model[block.propName]}
                            >
                              {block.option.map((item) => {
                                return (
                                  <ElRadio value={item.value}>
                                    {item.label}
                                  </ElRadio>
                                );
                              })}
                            </ElRadioGroup>
                          </div>
                        ),
                        checkbox: () => (
                          <div style={{ width: "100%" }}>
                            <ElCheckboxGroup
                            // v-model={formData.model[block.propName]}
                            >
                              {block.option.map((item) => {
                                return (
                                  <ElCheckbox value={item.value}>
                                    {item.label}
                                  </ElCheckbox>
                                );
                              })}
                            </ElCheckboxGroup>
                          </div>
                        ),
                        inspect: () => (
                          <SelfInspect
                            // v-model={formData.model[block.propName]}
                            v-model:renders={block.value}
                          ></SelfInspect>
                        ),
                        location: () => (
                          <ElInput
                            // v-model={formData.model[block.propName]}
                            placeholder="点击获取"
                            type={
                              block.tempType == "textarea" ? "textarea" : "text"
                            }
                            v-slots={{
                              suffix: () => (
                                <ElIcon>
                                  <Location />
                                </ElIcon>
                              ),
                            }}
                          ></ElInput>
                        ),
                        address: () => (
                          <>
                            <ElInput
                              // v-model={formData.model[block.propName]}
                              placeholder="请选择"
                              type={
                                block.tempType == "textarea"
                                  ? "textarea"
                                  : "text"
                              }
                            ></ElInput>
                            <ElInput
                              // v-model={formData.model[block.propName]}
                              placeholder="请输入具体位置"
                              type={
                                block.tempType == "textarea"
                                  ? "textarea"
                                  : "text"
                              }
                            ></ElInput>
                          </>
                        ),
                        signature: () => (
                          <>
                            <div
                              style={{
                                width: "100%",
                                color: "var(--font-hint-color)",
                                textAlign: "center",
                                backgroundColor: "white",
                                border: "1px solid var(--divider-color)",
                                padding: "2rem",
                              }}
                            >
                              点击去签名
                            </div>
                          </>
                        ),
                        upload: () => (
                          <>
                            <div style={{ width: "100%" }}>
                              <div
                                style={{
                                  width: "3rem",
                                  height: "3rem",
                                  backgroundColor: "var(--bg-color)",
                                  padding: "1.5rem",
                                  display: "flex",
                                  justifyContent: "center",
                                  alignItems: "center",
                                }}
                              >
                                <Camera
                                  style={{
                                    width: "1.5rem",
                                    height: "1.5rem",
                                    color: "var(--font-hint-color)",
                                  }}
                                ></Camera>
                              </div>
                            </div>
                          </>
                        ),
                      }[block.key]()}
                    </ElFormItem>
                  );
                })}
              </ElForm>
              <div className="formSubmit">
                <ElInput
                  v-model={data.value.container.btnName}
                  maxlength={4}
                  v-slots={{
                    suffix: () => (
                      <ElIcon>
                        <Edit style={{ color: "white" }} />
                      </ElIcon>
                    ),
                  }}
                ></ElInput>
              </div>
            </div>
          </div>
          <div className="editors-right">
            {/* 部分参数添加必填校验 */}
            <EditorPropsSet
              item={lastCheckItem.value}
              modelValue={data}
              onChangeItem={changeItem}
            />
          </div>
        </div>
      </>
    );
  },
});
